﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DHQGHN.DAL.BO.Admin;
using DHQGHN.Common;
using DHQGHN.DAL.Common;
using DHQGHN.PM0.Models.Admin;
using DHQGHN.PM0.Controllers;
using DHQGHN.PM0.Common.Attributes;
using DHQGHN.MVC.Controllers;

namespace DHQGHN.PM0.Controllers.Admin
{
    public class GenderController : BaseController
    {

        public const int REQUEST_ACTIVE = 1;
        GenderBO genderBO;
        log4net.ILog logger = log4net.LogManager.GetLogger(typeof(GenderController));

        public ActionResult Index(GenderModel a = null, int pageIndex = 0, string sort = "Id", string sortDir = "ASC", string currentId = null)
        {
            try
            {
                if (a == null) a = new GenderModel();
                if (string.IsNullOrEmpty(currentId)) currentId = string.Empty;

                ViewBag.ActiveMenus = ViewBag.ActiveMenus == null ? new System.Collections.Hashtable() : ViewBag.ActiveMenus;
                ViewBag.ActiveMenus[13] = "active";
                ViewBag.ActiveMenus[15] = "active";
                if (a == null)
                {
                    a = new GenderModel();
                }
                a.Deleted = 2;
                var model = search(a, pageIndex, currentId, false);
                return View("~/Views/Gender/Gender.cshtml", model);
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        /// Hiển thị form thêm mới giới tính
        [HttpPost]
        public ActionResult actionPrepareCreateOrUpdateGender(string id)
        {
            try
            {
                GenderModel model = null;
                if (!(String.IsNullOrWhiteSpace(id) && String.IsNullOrEmpty(id)))
                {
                    genderBO = new GenderBO();
                    model = new GenderModel(genderBO.GetGenderById(id));
                }
                if (model == null)
                {
                    model = new GenderModel();
                }
                if (Request.IsAjaxRequest())
                {
                    return PartialView("~/Views/Gender/_GenderModel.cshtml", model);
                }
                return View(model);
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        [HttpPost]
        public ActionResult actionSearch(GenderModel aModel = null, int pageIndex = 0, string sort = "GenderId", string sortDir = "ASC", string currentId =null)
        {
            try
            {
                if (aModel == null) aModel = new GenderModel();
                if (string.IsNullOrEmpty(currentId)) currentId = string.Empty;

                var model = search(aModel, pageIndex, currentId, false);
                return PartialView("~/Views/Gender/_GenderList.cshtml", model);
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        [AjaxValidateAntiForgeryToken]
        //Define request: Active = 1
        public ActionResult actionActive(string id)
        {
            try
            {
                if (Request.IsAjaxRequest())
                {
                    genderBO = new GenderBO();
                    bool result = genderBO.activeGender(id, REQUEST_ACTIVE);
                    if (result)
                    {
                        LogStream.Write(GetCurrentUserName(),
                         CommonData.AppName,
                         GetFunction(),
                         CommonData.GetListId(new string[] { id }),
                         Resources.Localization.ActionActiveCaption + " - actionActive");

                        return Json(JsonResponse.Json200("Khôi phục giới tính thành công!"));
                    }
                    else
                    {
                        return Json(JsonResponse.Json500("Xảy ra lỗi trong quá trình xử lý!"));
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
            return null;
        }

        /// Thêm mới giới tính
        [HttpPost]
        [ValidateInput(false)]
        [AjaxValidateAntiForgeryToken]
        public ActionResult actionCreateOrUpdateGender(GenderModel model)
        {
            try
            {
                if (Request.IsAjaxRequest())
                {
                    genderBO = new GenderBO();
                    if (model == null)
                    {
                        model = new GenderModel();
                    }
                    bool result = genderBO.createOrUpdateGender(model.toDALModel());
                    if (result)
                    {
                        LogStream.Write<GenderModel>(GetCurrentUserName(),
                            CommonData.AppName,
                            GetFunction(),
                            Resources.Localization.ActionSaveUpdateCaption + " - actionCreateOrUpdateGender", model);

                        if (!(String.IsNullOrEmpty(model.Gender_ID) || String.IsNullOrWhiteSpace(model.Gender_ID)))
                        {
                            return Json(JsonResponse.Json200("Cập nhật giới tính thành công!"));
                        }
                        else
                        {
                            return Json(JsonResponse.Json200("Thêm mới giới tính thành công!"));
                        }
                    }
                    else
                    {
                        return Json(JsonResponse.Json500("Xảy ra lỗi trong quá trình xử lý!"));
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
            return null;
        }

        [AjaxValidateAntiForgeryToken]
        public ActionResult actionDelete(string[] listID)
        {
            try
            {
                if (Request.IsAjaxRequest())
                {
                    genderBO = new GenderBO();
                    bool result = genderBO.deleteGender(listID);
                    if (result)
                    {
                        LogStream.Write(GetCurrentUserName(),
                            CommonData.AppName,
                            GetFunction(),
                            CommonData.GetListId(listID),
                            Resources.Localization.ActionDeleteCaption + " - actionDelete");

                        return Json(JsonResponse.Json200("Xóa giới tính thành công!"));
                    }
                    else
                    {
                        return Json(JsonResponse.Json500("Xảy ra lỗi trong quá trình xử lý!"));
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
            return null;
        }

        private DataPage<GenderModel> search(GenderModel aModel, int pageIndex, string currentId, bool compareEqual)
        {
            try
            {
                genderBO = new GenderBO();

                var DALModel = genderBO.GetDynamicListPaging(aModel.toDALModel(), PageSize, pageIndex, compareEqual);
                var models = new DataPage<GenderModel>();
                var lstItem = DALModel.Data;
                foreach (DHQGHN.DAL.Models.Admin.GenderModel gender in lstItem)
                {
                    models.Data.Add(new GenderModel(gender));
                }

                GenderModel model = null;
                if (!String.IsNullOrEmpty(currentId) && models.Data.Count > 0)
                {
                    model = models.Data.Find(user => user.Gender_ID == currentId);
                    models.CustomData = model;
                }
                else
                {
                    models.CustomData = aModel;
                }
                if (models.Data.Count > 0)
                {
                    //Tao component phan trang
                    var pagNative = new Pagination
                    {
                        ActionName = "actionSearch",
                        ModelName = "Gender",
                        CurrentPage = pageIndex,
                        InputSearchId = string.Empty,
                        TagetReLoadId = "gender-list",

                    };
                    pagNative.TotalRows = models.Data[0].RecordCount;
                    pagNative.CurrentRow = models.Data.Count;
                    ViewBag.Pagination = pagNative;
                }
                return models;
            }
            catch
            {
                throw;
            }
        }

        //Kiểm tra tên giới tính đã tồn tại chưa
        public JsonResult CheckExistGenderName(string name, string GENDER_ID)
        {
            try
            {
                var isExist = false;
                if (!string.IsNullOrEmpty(name))
                {
                    GenderModel genderModel = new GenderModel()
                    {
                        Name = name != null ? name.Trim() : name,
                        Deleted = 2
                    };

                    var model = search(genderModel, 0, string.Empty, true);

                    if (model.Data.Any())
                    {
                        var lstItem = model.Data;
                        foreach (GenderModel gender in lstItem)
                        {
                            if (!String.IsNullOrEmpty(GENDER_ID) || !String.IsNullOrWhiteSpace(GENDER_ID))
                            {
                                if (gender.Gender_ID != GENDER_ID)
                                {
                                    isExist = true;
                                    break;
                                }
                            }
                            else
                            {
                                //Kiem tra truong hop them moi
                                isExist = true;
                                break;
                            }
                        }
                    }
                }
                if (isExist)
                {
                    return Json(Resources.Localization.GenderNameExist);
                }
                else
                {
                    return Json(true, JsonRequestBehavior.AllowGet);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        //Kiểm tra mã giới tính đã tồn tại chưa
        public JsonResult CheckExistGenderCode(string code, string Gender_ID)
        {
            try
            {
                var isExist = false;
                if (!string.IsNullOrEmpty(code))
                {
                    GenderModel genderModel = new GenderModel()
                    {
                        Code = code == null ? code : code.Trim(),
                        Deleted = 2
                    };
                    var model = search(genderModel, 0, string.Empty, true);

                    if (model.Data.Any())
                    {
                        var lstItem = model.Data;
                        foreach (GenderModel gender in lstItem)
                        {
                            if (!String.IsNullOrWhiteSpace(Gender_ID) || !String.IsNullOrEmpty(Gender_ID))
                            {
                                if (!Equals(gender.Gender_ID, Gender_ID))
                                {
                                    isExist = true;
                                    break;
                                }
                            }
                            else
                            {
                                //Kiem tra truong hop them moi
                                isExist = true;
                                break;
                            }
                        }
                    }
                }
                if (isExist)
                {
                    return Json(Resources.Localization.GenderCodeExist);
                }
                else
                {
                    return Json(true, JsonRequestBehavior.AllowGet);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        private static string GetFunction()
        {
            return "Danh mục giới tính - GenderController";
        }
    }
}